from communication.asyncClient import AsyncClient
from public.config import get_config
from webpage.mei.urls import register_get, register_post
from django.shortcuts import render
from django.http import HttpResponse
import asyncio


async def air_conditioner_get_all():
    async with AsyncClient('air_conditioner_get_all') as client:
        return await client.send('')


async def air_conditioner_run(cmd):
    async with AsyncClient('air_conditioner_run') as client:
        return await client.send(cmd)


@register_get('admin')
def admin(request):
    password = request.GET.get('password')
    password_config = get_config('web_admin', 'password')

    return render(request, 'admin.html', {
        'password_correct': password == password_config,
        'cmd_list': asyncio.run(air_conditioner_get_all()),
    })


@register_post('admin/air_conditioner')
def admin_air_conditioner(request):
    password = request.GET.get('password')
    password_config = get_config('web_admin', 'password')

    if password != password_config:
        return HttpResponse('密码错误')

    cmd = request.POST.get('cmd')
    res = asyncio.run(air_conditioner_run(cmd))
    return HttpResponse(res)
